<%@page import="java.util.ArrayList"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="com.java.FamTree.*"%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<% 
	// Check to see if we're logged in.
	if (session.getAttribute("UserId") == null) {
	    response.sendRedirect("index.jsp"); // Send them away if they're not logged in.
	}

	//Check if user is admin
	if ((Boolean)session.getAttribute("IsAdmin") == false) {
	    response.sendRedirect("Home.jsp"); // Send back to home
	}
	
	int userId = -1;
	try {
	   userId = Integer.parseInt(request.getParameter("UserId"));
	} catch (NumberFormatException ex) {
	    userId = -1;
	}

	if(userId == -1) {
	    response.sendError(400, "Invalid UserId");
	}
	/*
	* Grab all persons that a user already has a permission with
	*/
	Connection con = null;
	Person person = null;
	ArrayList<Person> PersonPermissions = new ArrayList<Person>();
	try {
	    con = DriverManager.getConnection("jdbc:mysql://webdev.cs.uwosh.edu:4381/severa24", "severa24", "d450224");
	    PreparedStatement selectPerson = con.prepareStatement("SELECT p.PersonId, p.Name, COUNT(p.PersonId) AS Count FROM Person p LEFT JOIN Field f ON f.Person = p.PersonId AND f.UserId = ? GROUP BY p.PersonId ORDER BY Count DESC");

	    selectPerson.setInt(1, userId);
	    ResultSet rst = selectPerson.executeQuery();

	    while(rst.next()) {
	        person = new Person();
	        person.PersonId = rst.getInt(1);
	        person.Name = rst.getString(2);
	        person.PermissionCount = rst.getInt(3);
	        PersonPermissions.add(person);
	    }
	} catch (SQLException ex) { 
	    System.err.println(ex); 
	} finally {
	    if (con != null ) {
	        try {
	            con.close();
	        } catch (SQLException ex) {
	            System.err.println(ex);
	        }
	    }
	}

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Edit User Permission</title>
</head>
<body>
<Div style="text-align:right;background-color:#F0F0F0;" id="TopMenuBar" >
		<%
			out.print("<span id='WelcomSpan'>Welcome " + session.getAttribute("Username") + "  </span>");
			out.print("<a href='index.jsp'><button>Logout</button></a>");
			if((Boolean)session.getAttribute("IsAdmin")){
				out.print("<a href='Admin.jsp'><button>Admin</button></a>");
			}
		%>
	</Div>
	<link rel="stylesheet" type="text/css" href="Scripts/DataTables-1.9.4/media/css/jquery.dataTables.css">
 	<link rel="stylesheet" type="text/css" href="Scripts/DataTables-1.9.4/media/css/demo_table.css">
	<script type="text/javascript" src="Scripts/jquery-1.8.3.js"></script>
	<script type="text/javascript" src="Scripts/DataTables-1.9.4/media/js/jquery.dataTables.js"></script>
	<br/>
	<br/>
	<br/>
	<br/>
	<div>
		<div style="width:500px; margin:0 auto;">
			<table id="UserTable" class="display" align="center">
				<thead>
					<tr>
						<th>Person:</th>
						<th>Permission Count:</th>
						<th>Edit:</th>
					</tr>
				</thead>
				<tbody>
					<% 
						for(Person p : PersonPermissions){
							out.print("<tr><td>"+ p.Name + "</td><td>" + (p.PermissionCount < 2 ? p.PermissionCount - 1 : p.PermissionCount) + "</td><td><a href='EditPersonPermission.jsp?PersonId=" + p.PersonId + "&UserId="+userId+"'><button>Edit</button></a></td></tr>");
						}
					%>
				</tbody>
			</table>
			<br/>
			<br/>
			<a href='Admin.jsp'><button>Back To User Permissions</button></a>
		</div>
	</div>
	<script type="text/javascript">
		$(document).ready(function () {
			$('#UserTable').dataTable().fnSort( [ [1,'desc'] ] );
		});
	</script>
</body>
</html>